package com.woniuxy.opencv.controller;

import com.woniuxy.opencv.pojo.ParkingRecord;
import com.woniuxy.opencv.service.LicensePlateService;
import com.woniuxy.opencv.service.ParkingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/parking")
public class LicensePlateController {

    @Autowired
    private LicensePlateService licensePlateService;
    
    @Autowired
    private ParkingService parkingService;

    /**
     * 处理车辆入场（包含车牌识别）
     */
    @PostMapping("/entry/recognize")
    public ResponseEntity<Map<String, Object>> handleEntryWithRecognition(@RequestBody Map<String, String> request) {
        String base64Image = request.get("image");
        Map<String, Object> response = new HashMap<>();
        try {
            //识别车牌
            String licensePlate = licensePlateService.recognizeLicensePlate(base64Image);
            response.put("licensePlate", licensePlate);
            
            if ("未识别到车牌".equals(licensePlate) || licensePlate.startsWith("识别失败")) {
                response.put("success", false);
                response.put("message", licensePlate);
                return ResponseEntity.ok(response);
            }
            
            //记录入场
            ParkingRecord record = parkingService.handleEntry(licensePlate);
            
            response.put("success", true);
            response.put("record", record);
            response.put("message", "车辆入场成功");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("处理车辆入场时发生错误", e);
            response.put("success", false);
            response.put("message", "处理失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 处理车辆出场（包含车牌识别）
     */
    @PostMapping("/exit/recognize")
    public ResponseEntity<Map<String, Object>> handleExitWithRecognition(@RequestBody Map<String, String> request) {
        String base64Image = request.get("image");
        Map<String, Object> response = new HashMap<>();
        
        try {
            //识别车牌
            String licensePlate = licensePlateService.recognizeLicensePlate(base64Image);
            response.put("licensePlate", licensePlate);
            
            if ("未识别到车牌".equals(licensePlate) || licensePlate.startsWith("识别失败")) {
                response.put("success", false);
                response.put("message", licensePlate);
                return ResponseEntity.ok(response);
            }
            
            //记录出场
            ParkingRecord record = parkingService.handleExit(licensePlate);
            
            //计算费用
            double fee = parkingService.calculateParkingFee(record);
            
            response.put("success", true);
            response.put("record", record);
            response.put("fee", fee);
            response.put("message", "车辆出场成功");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("处理车辆出场时发生错误", e);
            response.put("success", false);
            response.put("message", "处理失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 查询车辆状态（包含车牌识别）
     */
    @PostMapping("/status/recognize")
    public ResponseEntity<Map<String, Object>> getStatusWithRecognition(@RequestBody Map<String, String> request) {
        String base64Image = request.get("image");
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 1. 识别车牌
            String licensePlate = licensePlateService.recognizeLicensePlate(base64Image);
            response.put("licensePlate", licensePlate);
            
            if ("未识别到车牌".equals(licensePlate) || licensePlate.startsWith("识别失败")) {
                response.put("success", false);
                response.put("message", licensePlate);
                return ResponseEntity.ok(response);
            }
            
            // 2. 查询状态
            ParkingRecord record = parkingService.queryCurrentRecord(licensePlate);
            
            response.put("success", true);
            response.put("record", record);
            if (record != null) {
                response.put("status", record.getStatus());
                response.put("startTime", record.getStartTime());
                if (record.getStatus() == 1) {
                    response.put("endTime", record.getEndTime());
                    response.put("fee", parkingService.calculateParkingFee(record));
                }
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("查询车辆状态时发生错误", e);
            response.put("success", false);
            response.put("message", "查询失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 手动输入车牌号查询状态
     */
    @GetMapping("/status/{licensePlate}")
    public ResponseEntity<Map<String, Object>> getStatus(@PathVariable String licensePlate) {
        Map<String, Object> response = new HashMap<>();
        try {
            ParkingRecord record = parkingService.queryCurrentRecord(licensePlate);
            response.put("success", true);
            response.put("record", record);
            if (record != null) {
                response.put("fee", parkingService.calculateParkingFee(record));
            }
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("查询车辆状态时发生错误", e);
            response.put("success", false);
            response.put("message", "查询失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }
} 